- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathSieveOfEratosthenes.java
38 lines (28 loc) Β· 663 Bytes
/
SieveOfEratosthenes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
packageLecture9;
// finds all prime numbers between 2 and n in O(log(log n))
publicclassSieveOfEratosthenes {
publicstaticvoidmain(String[] args) {
intn = 30;
soe_find_primes(n);
}
publicstaticvoidsoe_find_primes(intn) {
boolean[] primes = newboolean[n + 1];
for (inti = 0; i < primes.length; i++) {
primes[i] = true;
}
intnum = 2;
while (num * num < n) {
if (primes[num]) {
for (intmultiplier = 2; num * multiplier <= n; multiplier++) {
primes[num * multiplier] = false;
}
}
num++;
}
for (inti = 2; i < primes.length; i++) {
if (primes[i]) {
System.out.print(i + " ");
}
}
}
}